package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class loginCheckFilter implements Filter {

    /**
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //强转对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//      1.获取请求url。
        StringBuffer url = request.getRequestURL();
        log.info("url:{}",url);

//      2.判断请求urL中是否包含login，如果包含，说明是登录操作 放行
        if(url.toString().contains("login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            //结束当前方法
            return;
        }
//      3.获取请求头中的令牌(token)。
        String token = request.getHeader("token");
//      4.判断令牌是否存在，如果不存在，响应401。
        if(token == null){
            log.info("请求头token为空");
            // 第47行修复为：
            response.setStatus(401);
            //((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
//      5.解析token，如果解析失败，响应401。
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {

            log.info("令牌解析失败:{}",e.getMessage());
            response.setStatus(401);
            //((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;

        }
        log.info("claims:{}",claims);
//      6.放行。
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
